package com.lj.framework.web.config.redis;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.prefix}")
    private String PREFIX_KEY;


    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();

        //key
        //redisTemplate.setKeySerializer(new StringRedisSerializer());
        RedisKeySerialize redisKeySerialize = new RedisKeySerialize(PREFIX_KEY);//自定义KEY
        redisTemplate.setKeySerializer(redisKeySerialize);
        redisTemplate.setHashKeySerializer(redisKeySerialize);
        //jsonkey
        GenericJackson2JsonRedisSerializer genericFastJsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //FastJson2JsonRedisSerializer genericFastJsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        RedisKeySerialize redisKeySerialize = new RedisKeySerialize(PREFIX_KEY);//自定义KEY
        redisTemplate.setKeySerializer(redisKeySerialize);
        redisTemplate.setHashKeySerializer(redisKeySerialize);
        redisTemplate.setValueSerializer(redisKeySerialize);
        redisTemplate.setHashValueSerializer(redisKeySerialize);
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return redisTemplate;
    }

    /*
    //缓存设置
    @Bean
    public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))//设置缓存过期时间
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));   //设置序列化器
        RedisCacheManager build = RedisCacheManager.builder(lettuceConnectionFactory)
                .cacheDefaults(config)
                .build();
        return build;
    }*/
}
